package com.example.edianzu.somur.login.mvp.presenter;

import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.edianzu.somur.App;
import com.example.edianzu.somur.MainActivity;
import com.example.edianzu.somur.api.bean.LoginInfo;
import com.example.edianzu.somur.login.mvp.OnLoginListener;
import com.example.edianzu.somur.login.mvp.model.ILoginModel;
import com.example.edianzu.somur.login.mvp.model.LoginModelImpl;
import com.example.edianzu.somur.login.mvp.view.IView;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

import static android.content.ContentValues.TAG;

/**
 * Created by edianzu on 2017/7/10.
 */

public class LoginPresenterImpl implements ILoginPresenter{

    private IView iView;
    private ILoginModel iLoginModel;

    public LoginPresenterImpl(IView loginActivityImpl) {
        this.iView = loginActivityImpl;
        iLoginModel=new LoginModelImpl();
    }

    @Override
    public void login() {

        iLoginModel.login(iView.getPhoneNumber(), iView.getPassWord(), new OnLoginListener() {

            @Override
            public void onLoginSuccess(LoginInfo loginInfo) {

                if (loginInfo!=null) {

//                    设置极光推送的tag
                    Set<String> tags= new HashSet<>();
                    tags.add(loginInfo.getData().getMember_id()+"");
                    JPushInterface.setTags(App.getApp().getApplicationContext(),1,tags);
                    Log.d(TAG, "onLoginSuccess: "+loginInfo.getData().getMember_id()+"");

                    SharedPreferences sharedPreferences = App.getApp().getSharedPreferences();
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("phone", iView.getPhoneNumber());
                    editor.putString("password", iView.getPassWord());
                    editor.putString("company_id",loginInfo.getData().getCompany_id());
                    editor.commit();

                    Intent intent = new Intent(iView.getLoginActivity(), MainActivity.class);
                    intent.putExtra("member_id", loginInfo.getData().getMember_id());
                    intent.putExtra("login", loginInfo);

                    iView.getLoginActivity().startActivity(intent);

                    iView.getLoginActivity().finish();
                }
            }

            @Override
            public void onLoginError() {

                iView.loginError();
            }
        });

    }

    @Override
    public void clear() {

        iView.clearPhoneNumber();
        iView.clearPassWord();
    }
}
